from flask_appbuilder import ModelView
from flask_appbuilder.fieldwidgets import Select2Widget
from flask_appbuilder.models.sqla.interface import SQLAInterface
from app.models import SerialPortCategory, SerialPort
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from app import appbuilder, db


def category_query():
    return db.session.query(SerialPortCategory)


class SerialPortView(ModelView):
    datamodel = SQLAInterface(SerialPort)

    list_columns = ['name', 'port', 'category.name', 'readme']
    edit_form_extra_fields = {'category':  QuerySelectField('Something',
                                query_factory=category_query,
                                widget=Select2Widget(extra_classes="readonly"))}

    show_template = 'appbuilder/general/model/show_cascade.html'


class SerialCategoryView(ModelView):
    datamodel = SQLAInterface(SerialPortCategory)
    related_views = [SerialPortView]



appbuilder.add_view(SerialPortView, "Serial Port", icon="fa-folder-open-o", category="Company")
appbuilder.add_view(SerialCategoryView, "Serial Category", icon="fa-folder-open-o", category="Company")

